package com.yingpai.fitness.dvp_2_0.main.activity.shop;

import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.mcxtzhang.swipemenulib.SwipeMenuLayout;
import com.yingpai.fitness.R;
import com.yingpai.fitness.base.BaseResponse;
import com.yingpai.fitness.dvp_2_0.common.activity.CommonActivity;
import com.yingpai.fitness.dvp_2_0.common.adapter.BaseAdapterHelper;
import com.yingpai.fitness.dvp_2_0.common.adapter.QuickAdapter;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.callback.Callback;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.request.RequestType;
import com.yingpai.fitness.dvp_2_0.common.util.GsonUtil;
import com.yingpai.fitness.dvp_2_0.common.util.SharedPreferencesHelp;
import com.yingpai.fitness.dvp_2_0.common.util.constant.Contacts;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Constant;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Url;
import com.yingpai.fitness.entity.CartBean;
import com.yingpai.fitness.entity.ShopDetailMcipChildBean;
import com.yingpai.fitness.entity.wx.TokenBean;
import com.yingpai.fitness.dvp_2_0.common.view.XListView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;


public class CartActivity extends CommonActivity {

    @BindView(R.id.listview)
    ListView listview;
    @BindView(R.id.shop_cart_amount_price)
    TextView shopCartAmountPrice;
    @BindView(R.id.cart_amount_ll)
    LinearLayout cartAmountLl;
    @BindView(R.id.shop_cart_select_add_cb)
    CheckBox shopCartSelectAddCb;
    @BindView(R.id.totalNum)
    TextView totalNum;
    private QuickAdapter<CartBean.MapBean.ShoppingCartListBean> quickAdapter;
    private double price;
    private int flag;
    private List<String> shoppingCartIds;
    private TokenBean tokenBean;
    private CartBean mCartBean;
    private DecimalFormat df = new DecimalFormat("######.###");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStatusFlag(Contacts.NORMAL_STATUS);
        setContentView(R.layout.cart_activity);

    }


    @Override
    protected void initView() {
        setTitle("购物车");
        tokenBean = (TokenBean) SharedPreferencesHelp.getBean(Constant.TOKENBEAN);
        EventBus.getDefault().register(this);
        shoppingCartIds = new ArrayList<>();
        quickAdapter = new QuickAdapter<CartBean.MapBean.ShoppingCartListBean>(this, R.layout.item_shop_cart) {
            @Override
            protected void convert(final BaseAdapterHelper qhelper, final CartBean.MapBean.ShoppingCartListBean item) {
                qhelper.setText(R.id.title, item.getCont());

                XListView swip_listview = qhelper.getView(R.id.swip_listview);

                final QuickAdapter<CartBean.MapBean.ShoppingCartListBean.ListBean> swip_adapter = new QuickAdapter<CartBean.MapBean.ShoppingCartListBean.ListBean>(context, R.layout.item_swip_cart, item.getList()) {
                    @Override
                    protected void convert(final BaseAdapterHelper helper, final CartBean.MapBean.ShoppingCartListBean.ListBean child_item) {
                        View view = helper.getView(R.id.cart_line);
                        if (helper.getPosition() == item.getList().size() - 1) {
                            view.setVisibility(View.GONE);
                        } else {
                            view.setVisibility(View.VISIBLE);
                        }
                        final SwipeMenuLayout swipemenulayout = helper.getView(R.id.swipemenulayout);
                        final CheckBox checkbox = helper.getView(R.id.checkbox);
                        if (child_item.isChecked()) {
                            checkbox.setChecked(true);
                        } else {
                            checkbox.setChecked(false);
                        }
                        helper.setText(R.id.price, "" + df.format(child_item.getPrice() / 100));
                        helper.setText(R.id.title, child_item.getMerchandiseName());
                        ImageView photo = helper.getView(R.id.photo);
                        Glide.with(context)
                                .load(child_item.getPhotoUrl() == null ? "" : Arrays.asList(child_item.getPhotoUrl().split(",")).get(0))
                                .error(R.mipmap.default_small_bg)
                                .into(photo);
                        helper.setText(R.id.buyNumEt, child_item.getQuantity() + "");
                        child_item.setPropertyList(GsonUtil.jsonToList(child_item.getPropertyValue(), ShopDetailMcipChildBean.class));
                        StringBuilder stringBuilder = new StringBuilder();
                        for (int i = 0; i < child_item.getPropertyList().size(); i++) {
                            if (i == child_item.getPropertyList().size() - 1) {
                                stringBuilder.append(child_item.getPropertyList().get(i).getPropertyValue());
                            } else {
                                stringBuilder.append(child_item.getPropertyList().get(i).getPropertyValue() + ",");
                            }
                        }
                        helper.setText(R.id.mcip, stringBuilder.toString());

                        RelativeLayout buySubtractIv = helper.getView(R.id.buySubtractIv);//减号
                        RelativeLayout buyAddIv = helper.getView(R.id.buyAddIv);//加号
                        final TextView buyNumEt = helper.getView(R.id.buyNumEt);//数量

                        buyAddIv.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                showDialog(CartActivity.this, null);
                                HttpParams httpParams = new HttpParams();
                                httpParams.put("id", child_item.getId());
                                httpParams.put("merchandiseAmount", Integer.parseInt(buyNumEt.getText().toString()) + 1);
                                finalOkGo.request(RequestType.POST, Contacts.HOST_SERVER + Url.CART_MOTIFY_NUM, httpParams, Url.CART_MOTIFY_NUM, new Callback<BaseResponse>() {
                                    @Override
                                    public void onSuccess(BaseResponse baseResponse) {
                                        dismissDialog();
                                        if (baseResponse.getResult().equals(Constant.REQUEST_SUCCESS)) {
                                            child_item.setQuantity(child_item.getQuantity() + 1);
                                            flag += 1;
                                            if (checkbox.isChecked()) {
                                                price = price + child_item.getPrice();
                                                shopCartAmountPrice.setText("" + df.format(price / 100));
                                                totalNum.setText(flag + "");
                                            }
                                            notifyDataSetChanged();
                                        }
                                    }
                                });
                            }
                        });
                        buySubtractIv.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (Integer.parseInt(buyNumEt.getText().toString()) - 1 >= 1) {
                                    showDialog(CartActivity.this, null);
                                    HttpParams httpParams = new HttpParams();
                                    httpParams.put("id", child_item.getId());
                                    httpParams.put("merchandiseAmount", Integer.parseInt(buyNumEt.getText().toString()) - 1);
                                    finalOkGo.request(RequestType.POST, Contacts.HOST_SERVER + Url.CART_MOTIFY_NUM, httpParams, Url.CART_MOTIFY_NUM, new Callback<BaseResponse>() {
                                        @Override
                                        public void onSuccess(BaseResponse baseResponse) {
                                            dismissDialog();
                                            if (baseResponse.getResult().equals(Constant.REQUEST_SUCCESS)) {
                                                child_item.setQuantity(child_item.getQuantity() - 1);
                                                flag -= 1;
                                                if (child_item.isChecked()) {
                                                    price = price - child_item.getPrice();
                                                    shopCartAmountPrice.setText("" + df.format(price / 100));
                                                    totalNum.setText(flag + "");
                                                }
                                                notifyDataSetChanged();
                                            }
                                        }
                                    });
                                }
                            }
                        });
                        checkbox.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (child_item.isChecked()) {
                                    flag = flag - child_item.getQuantity();
                                    child_item.setChecked(false);
                                    price = price - child_item.getPrice() * child_item.getQuantity();
                                    shoppingCartIds.remove(child_item.getId() + "");
                                } else {
                                    flag = flag + child_item.getQuantity();
                                    child_item.setChecked(true);
                                    price = price + child_item.getPrice() * child_item.getQuantity();
                                    shoppingCartIds.add(child_item.getId() + "");
                                }
                                shopCartAmountPrice.setText("" + df.format(price / 100));
                                notifyDataSetChanged();
                                if (flag == 0) {
                                    shopCartSelectAddCb.setChecked(false);
                                } else if (flag > 0) {
                                    shopCartSelectAddCb.setChecked(true);
                                }
                                totalNum.setText(flag + "");
                            }
                        });
                        //删除
                        helper.getView(R.id.btnTop).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                showDialog(CartActivity.this, null);
                                HttpParams httpParams = new HttpParams();
                                httpParams.put("shoppingCartId", child_item.getId());
                                finalOkGo.request(RequestType.POST, Contacts.HOST_SERVER + Url.CART_DELETE, httpParams, Url.CART_DELETE, new Callback<BaseResponse>() {
                                    @Override
                                    public void onSuccess(BaseResponse baseResponse) {
                                        dismissDialog();
                                        if (baseResponse.getResult().equals(Constant.REQUEST_SUCCESS)) {
                                            if (child_item.isChecked()) {
                                                price = price - child_item.getPrice() * child_item.getQuantity();
                                                shoppingCartIds.remove(child_item.getId() + "");
                                                shopCartAmountPrice.setText("" + df.format(price / 100));
                                            }
                                            if (shopCartSelectAddCb.isChecked()) {
                                                flag = flag - child_item.getQuantity();
                                                totalNum.setText("" + flag);
                                                if (flag == 0) {
                                                    shopCartSelectAddCb.setChecked(false);
                                                }
                                            }
                                            //最外层的数据也相应的删掉，保持一致
                                            item.getList().remove(helper.getPosition());
                                            if (item.getList().size() == 0) {
                                                quickAdapter.remove(qhelper.getPosition());
                                            }
                                            //删除之后关闭侧滑
                                            swipemenulayout.smoothClose();
                                            quickAdapter.notifyDataSetChanged();
                                        } else {
                                            //删除失败，再去请求一次数据,让数据恢复正常
                                            try {
                                                showToast(baseResponse.getMsg());
                                                clearData();
                                                loadData();
                                            } catch (Exception e) {
                                                e.printStackTrace();
                                            }
                                        }
                                    }
                                });
                            }
                        });
                    }
                };
                swip_listview.setAdapter(swip_adapter);
            }
        };

        listview.setAdapter(quickAdapter);


    }

    @Override
    protected void initData() {
        loadData();
    }


    @Subscribe(threadMode = ThreadMode.POSTING)
    public void OnMessageEvent(String s) {
        if (Constant.UPDATA_CART.equals(s)) {
            loadData();
            //清空下面的一些数据
            clearData();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 请求网络数据
     */
    private void loadData() {
        showDialog(this, null);
        HttpParams httpParams = new HttpParams();
        httpParams.put("customerId", tokenBean.getId());
        finalOkGo.request(RequestType.POST, Contacts.HOST_SERVER + Url.CART_DATA, httpParams, Url.CART_DATA, new Callback<CartBean>() {
            @Override
            public void onSuccess(CartBean cartBean) {
                mCartBean = cartBean;
                dismissDialog();
                if (cartBean.getResult().equals(Constant.REQUEST_SUCCESS)) {
                    empty.setVisibility(View.GONE);
                    if (null != cartBean.getMap()) {
                        if (null != cartBean.getMap().getShoppingCartList() && cartBean.getMap().getShoppingCartList().size() > 0) {
                            quickAdapter.clear();
                            quickAdapter.addAll(cartBean.getMap().getShoppingCartList());
                            quickAdapter.notifyDataSetChanged();
                        }
                    } else {
                        showToast(cartBean.getMsg());
                    }
                } else {//没有数据，清空
                    empty.setVisibility(View.VISIBLE);
                    showToast(cartBean.getMsg());
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                dismissDialog();
                empty.setVisibility(View.VISIBLE);
            }
        });
    }

    /**
     * 清除一些数据
     */
    private void clearData() {
        totalNum.setText("0");//清空数量
        shopCartSelectAddCb.setChecked(false);
        price = 0.00;
        flag = 0;
        shopCartAmountPrice.setText("" + df.format(price / 100));
        shoppingCartIds.clear();
        quickAdapter.clear();
        quickAdapter.notifyDataSetChanged();
    }


    @Override
    @OnClick({R.id.shop_cart_select_add_cb, R.id.shop_cart_amount_immediate_settlement})
    public void onViewClicked(View view) {
        super.onViewClicked(view);
        switch (view.getId()) {
            case R.id.shop_cart_select_add_cb:
                if (shopCartSelectAddCb.isChecked()) {
                    shopCartSelectAddCb.setChecked(true);
                    price = 0.00;
                    flag = 0;//从头开始加
                    for (int i = 0; i < quickAdapter.getCount(); i++) {
                        List<CartBean.MapBean.ShoppingCartListBean.ListBean> list = quickAdapter.getItem(i).getList();
                        for (int j = 0; j < list.size(); j++) {
                            quickAdapter.getItem(i).getList().get(j).setChecked(true);
                            flag = flag + quickAdapter.getItem(i).getList().get(j).getQuantity();

                            price = price + quickAdapter.getItem(i).getList().get(j).getPrice() *
                                    quickAdapter.getItem(i).getList().get(j).getQuantity();
                            shoppingCartIds.add(quickAdapter.getItem(i).getList().get(j).getId() + "");
                        }
                    }
                    totalNum.setText("" + flag);
                } else {
                    totalNum.setText("0");//清空数量
                    shopCartSelectAddCb.setChecked(false);
                    price = 0.00;
                    flag = 0;
                    shoppingCartIds.clear();
                    for (int i = 0; i < quickAdapter.getCount(); i++) {
                        for (int j = 0; j < quickAdapter.getItem(i).getList().size(); j++) {
                            quickAdapter.getItem(i).getList().get(j).setChecked(false);
                        }
                    }
                }
                shopCartAmountPrice.setText("" + df.format(price / 100));
                quickAdapter.notifyDataSetChanged();
                break;
            case R.id.shop_cart_amount_immediate_settlement:
                if (shoppingCartIds != null && shoppingCartIds.size() != 0) {
                    String ids = "";
                    for (int i = 0; i < shoppingCartIds.size(); i++) {
                        if (i == shoppingCartIds.size() - 1) {
                            ids = ids + shoppingCartIds.get(i);
                        } else if (i == 0) {
                            ids = shoppingCartIds.get(i) + ",";
                        } else {
                            ids = ids + shoppingCartIds.get(i) + ",";
                        }
                    }
                    Bundle bundle = new Bundle();
                    bundle.putInt("source", Constant.NUM_2);
                    bundle.putString("shoppingCartIds", ids);
                    startActivity(PurchaseOrderActivity.class, bundle);
                } else {
                    showToast("请先选择要购买的商品");
                }
                break;
        }
    }
}
